/*
 * Created: Author: Aléx Carvalho / Date: Mar 10, 2015
 * 
 * Changed: $Author: ac280593@gmail.com $ / $Date: 2015-06-12 03:38:01 +0000 (Fri, 12 Jun 2015) $
 */
package com.cpm.servlets;

import com.cpm.ServiceLocator;
import com.cpm.aggregate.SessionAttribute;
import com.cpm.context.SessionContext;
import com.cpm.view.Pages;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

@WebFilter(filterName = "FilterLogin", urlPatterns = {"/admin/*"})
public class ServletFilter implements Filter {

    @Override
    public void init(FilterConfig fc) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

//        HttpServletRequest HttpRequest = (HttpServletRequest) request;
//        if( HttpRequest.getSession().getAttribute( SessionAttribute.ACTIVE_USER.toString() ) != null )
        
        if (ServiceLocator.lookup(SessionContext.class).getAttribute(SessionAttribute.ACTIVE_USER) != null) {
            chain.doFilter(request, response);
        }
        else {
            request.getRequestDispatcher(Pages.LOGIN).forward(request, response);
        }
    }

    @Override
    public void destroy() {
    }
}